var http = require('http')
var fs = require('fs')
var url = require('url')
var port = process.argv[2]

if (!port) {
  console.log(' 需指定端口号! \n 如·：node server.js 8888')
  process.exit(1)
}

var server = http.createServer(function (request, response) {
  var parsedUrl = url.parse(request.url, true)
  var pathWithQuery = request.url
  var queryString = ''
  if (pathWithQuery.indexOf('?') >= 0) { queryString = pathWithQuery.substring(pathWithQuery.indexOf('?')) }
  var path = parsedUrl.pathname
  var query = parsedUrl.query
  var method = request.method

  /******** 核心 ************/

  console.log('接受到请求，路径（带查询参数）为：' + pathWithQuery)

  if (path === '/') {
    response.statusCode = 200 // 状态码
    response.setHeader('Content-Type', 'text/html;charset=utf-8')  //响应内容的类型/语法
    response.write(`
    <!DOCTYPE html>
    <head>
    <link rel="stylesheet" href="/x">
    </head>
    <body>
    <h1>This is a title</h1>
    <script src="/y"> </script>
    </body>
    `) //相应的返回内容
    response.end()  //表示响应可以发给用户了
  } else if (path === '/x') {
    response.statusCode = 200
    response.setHeader('Content-Type', 'text/css;charset=utf-8')
    response.write(`body{color: red;}`)
    response.end()
  } else if (path === '/y') {
    response.statusCode = 200
    response.setHeader('Content-type', 'text/javascript;charset=utf-8')
    response.write(`console.log('Citing JS code.')`)
    response.end()
  }
  else {
    response.statusCode = 404
    response.setHeader('Content-Type', 'text/html;charset=utf-8')
    response.write(`你输入的路径不存在对应的内容`)
    response.end()
  }

  /******** end ************/
})

server.listen(port)
console.log(' 监听 ' + port + ' 成功\n 可打开 http://localhost:' + port)

